/**
 * EJ珠宝系统可复用功能函数库
 * 包含图片查看器等可复用功能
 */

// 全局变量用于存储图片查看器状态
let ejjImageModal = null;
let currentImageIndex = 0;
let currentProductImages = [];

/**
 * 显示指定产品ID的所有图片
 * @param {string} productId - 产品ID
 */
function showJadeImages(productId) {
    if (!productId) {
        console.error('产品ID不能为空');
        return;
    }

    // 显示加载状态
    showLoading('正在加载图片...');

    // 调用后端API获取图片列表
    fetch(`/get_jade_images?product_id=${encodeURIComponent(productId)}`)
        .then(response => {
            console.log('获取图片列表响应:', response);
            return response.json();
        })
        .then(data => {
            console.log('获取图片列表数据:', data);
            if (data.res === 'ok') {
                // 初始化图片查看器
                initImageModal(data.images, productId);
                // 显示第一张图片
                showImage(0);
            } else {
                alert('获取图片失败: ' + data.msg);
            }
        })
        .catch(error => {
            console.error('获取图片列表失败:', error);
            alert('获取图片列表失败，请检查网络连接');
        })
        .finally(() => {
            // 隐藏加载状态
            hideLoading();
        });
}

/**
 * 初始化图片查看模态框
 * @param {Array} images - 图片文件列表
 * @param {string} productId - 产品ID
 */
function initImageModal(images, productId) {
    // 清理现有的模态框和事件监听器
    cleanupImageModal();

    // 创建模态框HTML
    const modalHtml = `
        <div class="modal fade" id="ejjImageModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-lg modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">产品图片查看器 - ${productId}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="text-center mb-3">
                            <img id="ejjMainImage" src="" class="img-fluid rounded" 
                                 style="max-height: 500px; object-fit: contain;" 
                                 alt="产品图片">
                        </div>
                        
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <button class="btn btn-outline-primary" onclick="prevImage()">
                                <i class="bi bi-chevron-left"></i> 上一张
                            </button>
                            
                            <span id="ejjImageCounter" class="text-muted">0 / 0</span>
                            
                            <button class="btn btn-outline-primary" onclick="nextImage()">
                                下一张 <i class="bi bi-chevron-right"></i>
                            </button>
                        </div>
                        
                        <!-- 缩略图导航 -->
                        <div class="thumbnails-container" id="ejjThumbnails" 
                             style="display: flex; overflow-x: auto; gap: 8px; padding: 10px 0;">
                            <!-- 缩略图将通过JavaScript动态添加 -->
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    </div>
                </div>
            </div>
        </div>
    `;

    // 添加到body
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    ejjImageModal = new bootstrap.Modal(document.getElementById('ejjImageModal'));
    
    // 存储当前图片数据
    currentProductImages = images;
    currentImageIndex = 0;

    // 创建缩略图
    createThumbnails(images, productId);

    // 显示模态框
    ejjImageModal.show();

    // 添加键盘事件监听
    document.addEventListener('keydown', handleKeyboardNavigation);
    
    // 模态框关闭时清理
    document.getElementById('ejjImageModal').addEventListener('hidden.bs.modal', function () {
        cleanupImageModal();
    });
}

/**
 * 清理图片模态框和相关资源
 */
function cleanupImageModal() {
    // 移除键盘事件监听
    document.removeEventListener('keydown', handleKeyboardNavigation);
    
    // 移除现有的模态框
    const existingModal = document.getElementById('ejjImageModal');
    if (existingModal) {
        existingModal.remove();
    }
    
    // 重置全局变量
    ejjImageModal = null;
    currentProductImages = [];
    currentImageIndex = 0;
}

/**
 * 创建缩略图导航
 * @param {Array} images - 图片文件列表
 * @param {string} productId - 产品ID
 */
function createThumbnails(images, productId) {
    const thumbnailsContainer = document.getElementById('ejjThumbnails');
    thumbnailsContainer.innerHTML = '';

    images.forEach((image, index) => {
        const thumb = document.createElement('img');
        thumb.src = `/serve_jade_image?product_id=${productId}&filename=${encodeURIComponent(image)}`;
        thumb.className = 'thumbnail';
        thumb.style = 'width: 60px; height: 60px; object-fit: cover; cursor: pointer; border: 2px solid transparent; border-radius: 4px;';
        thumb.alt = `缩略图 ${index + 1}`;
        thumb.onclick = () => showImage(index);
        thumb.onerror = function() {
            this.src = '/static/images/default_cover.jpg';
        };
        thumbnailsContainer.appendChild(thumb);
    });
}

/**
 * 显示指定索引的图片
 * @param {number} index - 图片索引
 */
function showImage(index) {
    if (index < 0 || index >= currentProductImages.length) {
        return;
    }

    currentImageIndex = index;
    const imageName = currentProductImages[index];
    const productId = document.querySelector('#ejjImageModal .modal-title').textContent.split(' - ')[1];
    
    const mainImage = document.getElementById('ejjMainImage');
    mainImage.src = `/serve_jade_image?product_id=${productId}&filename=${encodeURIComponent(imageName)}`;
    
    // 更新计数器
    document.getElementById('ejjImageCounter').textContent = 
        `${currentImageIndex + 1} / ${currentProductImages.length}`;
    
    // 更新缩略图选中状态
    updateThumbnailSelection();
    
    // 图片加载错误处理
    mainImage.onerror = function() {
        this.src = '/static/images/default_cover.jpg';
    };
}

/**
 * 更新缩略图选中状态
 */
function updateThumbnailSelection() {
    const thumbnails = document.querySelectorAll('.thumbnail');
    thumbnails.forEach((thumb, index) => {
        if (index === currentImageIndex) {
            thumb.style.borderColor = '#007bff';
        } else {
            thumb.style.borderColor = 'transparent';
        }
    });
}

/**
 * 显示下一张图片
 */
function nextImage() {
    if (currentImageIndex < currentProductImages.length - 1) {
        showImage(currentImageIndex + 1);
    } else {
        // 循环到第一张
        showImage(0);
    }
}

/**
 * 显示上一张图片
 */
function prevImage() {
    if (currentImageIndex > 0) {
        showImage(currentImageIndex - 1);
    } else {
        // 循环到最后一张
        showImage(currentProductImages.length - 1);
    }
}

/**
 * 键盘导航处理
 * @param {KeyboardEvent} event - 键盘事件
 */
function handleKeyboardNavigation(event) {
    if (event.key === 'ArrowRight') {
        nextImage();
    } else if (event.key === 'ArrowLeft') {
        prevImage();
    } else if (event.key === 'Escape') {
        if (ejjImageModal) {
            ejjImageModal.hide();
        }
    }
}

/**
 * 显示加载状态
 * @param {string} message - 加载提示信息
 */
function showLoading(message = '加载中...') {
    // 移除现有的加载提示
    hideLoading();
    
    const loadingHtml = `
        <div class="position-fixed top-0 start-0 w-100 h-100 d-flex align-items-center justify-content-center" 
             style="background-color: rgba(0,0,0,0.5); z-index: 9999;">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">${message}</span>
            </div>
            <span class="ms-2 text-white">${message}</span>
        </div>
    `;
    
    document.body.insertAdjacentHTML('beforeend', loadingHtml);
}

/**
 * 隐藏加载状态
 */
function hideLoading() {
    const loadingElement = document.querySelector('.position-fixed[style*="background-color: rgba(0,0,0,0.5)"]');
    if (loadingElement) {
        loadingElement.remove();
    }
}

/**
 * 使产品ID单元格可点击
 * @param {string} selector - 选择器，默认为包含产品ID的td元素
 */
function makeProductIdsClickable(selector = 'td:nth-child(3)') {
    // 等待页面加载完成
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            initClickableProductIds(selector);
        });
    } else {
        initClickableProductIds(selector);
    }
}

/**
 * 初始化可点击的产品ID
 * @param {string} selector - 选择器
 */
function initClickableProductIds(selector) {
    const productIdCells = document.querySelectorAll(selector);
    
    productIdCells.forEach(cell => {
        const productId = cell.textContent.trim();
        if (productId) {
            // 添加点击样式和事件
            cell.style.cursor = 'pointer';
            cell.style.color = '#007bff';
            cell.title = '点击查看产品图片';
            cell.onclick = function() {
                showJadeImages(productId);
            };
            
            // 添加鼠标悬停效果
            cell.addEventListener('mouseenter', function() {
                this.style.textDecoration = 'underline';
            });
            cell.addEventListener('mouseleave', function() {
                this.style.textDecoration = 'none';
            });
        }
    });
}

// 自动使产品ID可点击（如果页面中有产品ID单元格）
document.addEventListener('DOMContentLoaded', function() {
    // 延迟执行以确保表格数据已加载
    setTimeout(() => {
        makeProductIdsClickable();
    }, 1000);
});

/**
 * 检查并初始化销售结算页面的图片功能
 * 这个函数专门用于销售结算页面，确保图片查看器正常工作
 */
function initSaleSettleImageFunctions() {
    // 检查当前页面是否为销售结算页面
    const isSaleSettlePage = document.title.includes('销售结算管理') || 
                            window.location.pathname.includes('sale_settle');
    
    if (isSaleSettlePage) {
        console.log('初始化销售结算页面图片功能');
        
        // 重写makeProductIdsClickable函数，使其在销售结算页面不执行任何操作
        if (typeof window.makeProductIdsClickable === 'function') {
            window.makeProductIdsClickable = function() {
                console.log('销售结算页面已禁用产品ID点击功能');
                // 什么都不做，保持stock_id为普通文本
            };
        }
        
        // 确保showJadeImages函数在全局可用
        if (typeof window.showJadeImages !== 'function') {
            window.showJadeImages = function(productId) {
                console.error('showJadeImages函数未正确加载');
                alert('图片查看功能暂不可用');
            };
        }
    }
}

// 页面加载时初始化销售结算页面图片功能
document.addEventListener('DOMContentLoaded', function() {
    initSaleSettleImageFunctions();
});
